<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="82px">
      <el-form-item label="所属学校ID" prop="schoolId">
        <el-input
          v-model="queryParams.schoolId"
          placeholder="请输入所属学校ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称 (如：初一(1)班)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input
          v-model="queryParams.grade"
          placeholder="请输入年级 (如：初一、高二)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['schoolmanage:classes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['schoolmanage:classes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['schoolmanage:classes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['schoolmanage:classes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级ID" align="center" prop="classId" />
      <el-table-column label="所属学校ID" align="center" prop="schoolId" />
      <el-table-column label="所属学校名称" align="center" prop="schoolName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['schoolmanage:classes:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['schoolmanage:classes:remove']">删除</el-button>
          <el-button link type="danger" icon="MessageBox" @click="handleGoToExam(scope.row)">配置考试信息</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="classesRef" :model="form" :rules="rules" label-width="95px">
        <el-form-item label="所属学校ID" prop="schoolId">
          <el-input v-model="form.schoolId" disabled />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称 (如：初一(1)班)" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级 (如：初一、高二)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Classes">
import { listClasses, getClasses, delClasses, addClasses, updateClasses } from "@/api/schoolmanage/classes"
import {useExampleStore} from "@/stores/exampleStore.js";
import { useRouter } from 'vue-router'; // 新增：引入 useRouter
const router = useRouter(); // 新增：获取路由实例

const { proxy } = getCurrentInstance()

const classesList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    classId: null,
    schoolId: useExampleStore().school,
    schoolName: null,  // 新增：用于表单回显（如果需要）
    className: null,
    grade: null,
    createTime: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: useExampleStore().school,
    className: null,
    grade: null,
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    className: [
      { required: true, message: "班级名称 (如：初一(1)班)不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

const handleGoToExam = () => {
  // 使用路由跳转到考试配置页面，并携带学生信息作为参数
  router.push({
    path: '/exam/config'
  });
};

/** 查询班级管理列表 */
function getList() {
  loading.value = true
  queryParams.value.schoolId = useExampleStore().school
  listClasses(queryParams.value).then(response => {
    classesList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error=>{
    console.error("获取列表失败：",error);
    loading.value = false;
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    classId: null,
    schoolId: useExampleStore().school,
    className: null,
    grade: null,
    createTime: null
  }
  proxy.resetForm("classesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.classId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加班级管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _classId = row.classId || ids.value
  getClasses(_classId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改班级管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classesRef"].validate(valid => {
    if (valid) {
      if (form.value.classId != null) {
        updateClasses(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addClasses(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _classIds = row.classId || ids.value;
  proxy.$modal.confirm('是否确认删除班级管理编号为"' + _classIds + '"的数据项？')
      .then(function() {
        // 调用删除接口
        return delClasses(_classIds);
      })
      .then((response) => {
        // 判断删除结果
        if (response.success) {
          getList(); // 刷新列表
          proxy.$modal.msgSuccess("删除成功"); // 成功提示
        } else {
          // 失败提示后端返回的错误信息
          proxy.$modal.msgError(response.errorMsg);
        }
      })
      .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('schoolmanage/classes/export', {
    ...queryParams.value
  }, `classes_${new Date().getTime()}.xlsx`)
}

getList()
</script>
